package org.agle4j.algorithm.array.ordered;

import java.util.ArrayList;
import java.util.List;

/**
 * 有序数组的操作
 * 
 * @author hanyx
 */
public class OrderArrayWithValue {

	private int[] datas;
	private int currentIndex = 0;

	public OrderArrayWithValue(int index) {
		datas = new int[index];
	}

	public int insert(int data) {
		// 假设是升序
		int index = 0;
		// 1.查找数据data应该存放的位置 index
		for (index = 0; index < currentIndex; index++) {
			if (datas[index] > data) {
				break;
			}
		}
		// 2.把这个位置及其后面数据,向后移动一位
		for (int i = currentIndex; i > index; i--) {
			datas[i] = datas[i - 1];
		}
		// 3.把data存放到应该存放的位置
		datas[index] = data ;
		
		currentIndex ++ ;
		return currentIndex -1;
	}

	public void remove(int data) {
		int index = getIndex(0, data);
		while (index != -1) {
			for (int i = index; i < this.currentIndex; i++) {
				datas[i] = datas[i + 1];
			}
			currentIndex--;
			index = getIndex(index, data);
		}
	}

	public int getIndex(int begin, int data) {
		for (int i = begin; i < currentIndex; i++) {
			if (datas[i] == data) {
				return i;
			}
		}
		return -1;
	}

	public List<Integer> searchOne(int data) {
		List<Integer> intList = new ArrayList<>();
		int index = getIndex(0, data);
		while (index != -1) {
			intList.add(index);
			index = getIndex(index + 1, data);
		}
		return intList;
	}

	public void printDatas() {
		for (int i = 0; i < this.currentIndex; i++) {
			System.out.println(this.datas[i]);
		}
		System.out.println("////////////////////");
	}
}
